<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Helper\RequestHelper;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RateLimitMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $ip = RequestHelper::getClientIp($request);
        $classAndMethod = RequestHelper::getClassAndMethod($request);
        if (!is_null($classAndMethod) && $ip) {
            $class = $classAndMethod[0] ?? '';
            $method = $classAndMethod[1] ?? '';
            if (!empty($class) && !empty($method)) {
                if (!RequestHelper::rateLimit($ip . '_' . $class . '_' . $method, 30, 30)) {
                    return Context::get(ResponseInterface::class)->withStatus(403);
                }
            }
        }
        return $handler->handle($request);
    }
}
